package com.app.java.url;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UrlTestThread implements Runnable {

	private static int senderId = 0;

	private int id;
	private URL url;
	private List<String> queue;
	private Thread thread;
	private Logger logger;
	private int processTime;
	private long timer;
	
	public UrlTestThread(URL url, List<String> queue, int processTime)
	{
		id               = ++senderId;
		this.url         = url;
		this.queue       = queue;
		this.processTime = processTime;
		logger = LoggerFactory.getLogger(getClass());
	}

	public boolean isAlive() {
		return (thread != null);
	}

	public boolean startSender() {
		// return true if sender is started now
		if (thread == null) {
			logger.info("Start mt sender " + id);
			thread = new Thread(this);
			thread.start();
			return true;
		}
		// return false if sender was already started
		else
			return false;
	}

	public void close() {
		logger.info("Mt sender " + id + " close");
		thread = null;
		url = null;
	}

	public void run() {
		while (!queue.isEmpty()) {
			HttpURLConnection conn = null;
			long timeDiff = System.currentTimeMillis() - timer;

			try {
				if (!queue.isEmpty()) {
					// get Mt message from array list
					String mt = queue.remove(0);

					// chun03 start
					// setup connection
					conn = (HttpURLConnection) url.openConnection();
					conn.setRequestMethod("POST");
					conn.setDoOutput(true);
					conn.setDoInput(true);
					conn.setReadTimeout(5000);
					conn.setConnectTimeout(5000);
					conn.connect();

					// send request
					BufferedOutputStream urlOut = new BufferedOutputStream(conn.getOutputStream());
					PrintWriter pw = new PrintWriter(urlOut);
					pw.println(mt);
					pw.flush();
					pw.close();
					
					
					urlOut.write(mt.getBytes("ISO-8859-1"));
					urlOut.flush();
					urlOut.close();
					
					BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String str = null;
					while ((str = br.readLine()) != null)
						System.out.println(str);

				}
			}
			// parser exception
			catch (Throwable t) {
				logger.error("Parser error:\n");
			} finally {
				try {
					if (conn != null) {
						conn.disconnect();
						conn = null;
					}
					// sleep to release CPU time
					logger.debug("sender " + id + ": b4 sleep");
					if (timeDiff < processTime) {
						Thread.sleep(processTime - timeDiff);
					} else
						Thread.sleep(500);
					logger.debug("sender " + id + ": after sleep");
				} catch (Exception e) {
				}
			}
		}

		// kill thread
		thread = null;
		logger.info("Close mt sender " + id);
	}
}
